package o2o.web.actions.order.admin;

import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import jPush.dao.JPushMessage;
import notice.dao.NoticeType;
import o2o.cache.comment.OrderCommentMemory;
import o2o.cache.company.postman.PostCompanyMemory;
import o2o.cache.company.postman.PostmanSignCompanyMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.order.OrderPayMemory;
import o2o.cache.order.OrderStatusMemory;
import o2o.cache.order.PostmanGrabMemory;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.sys.SysConfigDepositMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.wallet.UserWalletMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.company.postman.PostmanSignCompanyInfo;
import o2o.dao.PO.company.postman.SIGN_COMPANY_STATUS;
import o2o.dao.PO.order.*;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.shop.COMMENT_VERIFY_STATE;
import o2o.dao.PO.shop.ShopCommentInfo;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.UserWallet;
import o2o.dao.VO.order.OrderCommentInfoVO;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.task.mixComTel.MixComTelTask;
import o2o.utils.CommonUtils;
import o2o.web.actions.notice.Notice;
import o2o.web.actions.order.OrderMan;
import o2o.web.actions.order.shop.ShopOrderController;
import o2o.web.actions.pay.OrderPay;
import o2o.web.actions.sys.GrabOrderModeMan;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.transaction.Transactional;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

//管理员订单操作
@Controller
public class AdminOrderController {
    //-----------------------------管理员

    //管理员帮商家接单
    @RequestMapping(value = "/admin/order/sure")
    @ResponseBody
    public String order_shop_sure(String token, String sysAppKey, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        if (null != orderInfo.getOrderType()
                &&
                (0 == ORDER_TYPE.SHOP_SERVICE - orderInfo.getOrderType() //维修订单
                        || 0 == ORDER_TYPE.SHOP_RESCUE - orderInfo.getOrderType()//救援
                )) {
            return AjaxResult.errorResult("不支持此订单类型的的订单");
        }

        // 父类订单
        if (OrderMan.isMultipleParentOrder(orderNo)) {
            try {
                sure_parent_order(sysAppKey, orderNo, user.getUsername());
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult(e.getMessage());
            }
        } else {
            //获取店铺对象
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
            if (null == shopInfo) {
                return AjaxResult.errorResult("店铺已不存在，请查证");
            }
            //0 锁定  1正常
            if (0 == shopInfo.getIsLock()) {
                return AjaxResult.errorResult("您的店铺已锁定，无法接单");
            }

            // 系统已经帮商家接单了
            if (null != orderInfo.getShopSureBySys() && 0 == 1 - orderInfo.getShopSureBySys()) {
                return AjaxResult.successResult();
            }
            if (null != orderInfo.getShopSureTime() && orderInfo.getShopSureTime() > 0) {
//                return AjaxResult.errorResult("已接单，请刷新查看");
                System.out.println("后台重复接单：" + orderNo);
                return AjaxResult.successResult();
            }

            ResultInfo resultInfo = ShopOrderController.sureOrder(sysAppKey, shopInfo, orderInfo, user.getUsername(), true);

            if (null != resultInfo) {
                if (!resultInfo.isSuccess()) {
                    return AjaxResult.errorResult(resultInfo.getError());
                }
            } else {
                return AjaxResult.errorResult("接单失败，请稍后再试");
            }

        }

//        //获取店铺对象
//        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
//        if (null == shopInfo) {
//            return AjaxResult.errorResult("店铺已不存在，请查证");
//        }
//        //0 锁定  1正常
//        if (0 == shopInfo.getIsLock()) {
//            return AjaxResult.errorResult("您的店铺已锁定，无法接单");
//        }
//
//        ResultInfo resultInfo = ShopOrderController.sureOrder(sysAppKey, shopInfo, orderInfo, user.getUsername(), true);
//        if (null != resultInfo) {
//            if (!resultInfo.isSuccess()) {
//                return AjaxResult.errorResult(resultInfo.getError());
//            }
//        } else {
//            return AjaxResult.errorResult("接单失败，请稍后再试");
//        }
        return AjaxResult.successResult();
    }

    // 完成订单
    @RequestMapping(value = "/admin/order/over")
    @ResponseBody
    public String order_shop_over(String token, String sysAppKey, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        if (null == orderInfo.getOrderType()) {
            return AjaxResult.errorResult("不支持该类型的订单");
        }

        if (0 == ORDER_TYPE.SHOP_GOODS - orderInfo.getOrderType()
                || 0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType()
                || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()) {

        } else {
            return AjaxResult.errorResult("不支持此订单类型的的订单");
        }

        // 父类订单
        if (OrderMan.isMultipleParentOrder(orderNo)) {
            // todo 聚合订单还不知道怎么处理

        } else {
            //获取店铺对象
//            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
//            if (null == shopInfo) {
//                return AjaxResult.errorResult("店铺已不存在，请查证");
//            }
//
            if (0 == orderInfo.getOrderStatus() - ORDER_STATUS.POSTMAN_DAODIAN
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.SHOP_SURE
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.SHOP_READY
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.SHOP_PUSH_GOODS
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.POSTMAN_PULL_GOODS
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.POSTMAN_DAODIAN
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.PEISONG
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.POSTMAN_SURE
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.POSTMAN_ZD_SURE_BEFORE_SHOP
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.POSTMAN_REFUSED
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.POSTMAN_CANT_FINISH
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.POSTMAN_PICK_POINT
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_SUER
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.SECONDARY_POSTMAN_PULL_GOODS
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_DAODIAN
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_PULL
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_POINT
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_DAODIAN
                    || 0 == orderInfo.getOrderStatus() - ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_INNER_SHOP) {

//                //分成
//                ResultInfo resultInfo = OrderPay.distributeMoney(orderInfo, orderNo, user.getUsername());
//                if (null != resultInfo && !resultInfo.isSuccess()) {
//                    System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
//                }

                ResultInfo resultInfo = OrderPay.distributeMoney(orderInfo, orderNo, user.getUsername());

                if (null != resultInfo && !resultInfo.isSuccess()) {
                    System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
                }

                //完成订单
                OrderMan.finishOrder(orderNo, user.getUsername(), orderInfo);
            } else {
                return AjaxResult.errorResult("此状态不允许操作");
            }
        }

        return AjaxResult.successResult();
    }
    //TODO 批量指派配送员兼容 未完成，存在回滚问题
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/postman/addPassTokenAll")
    @ResponseBody
    @Transactional(rollbackOn = RuntimeException.class)
    public String order_postman_addAll(@RequestParam String[] orderNo,@RequestParam String username){
            Arrays.stream(orderNo).forEach(e->{
                // 批量判断和填充sql;
                String result = this.order_postman_add(null,null,e,username);

                if(!result.contains("\"status\":1}")){
                    throw new RuntimeException(result);
                }
            });


        return AjaxResult.successResult();
    }




    //指定配送员 管理员（单个）
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/postman/assignPostman")
    @ResponseBody
    public String order_postman_add(String sysAppKey, Long companyId, String orderNo, String username) {
        //跳过验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getSuperAdmin();
        if (user == null)  {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有权限
//        if (!User.hasServiceAuth(user.getUserType())) {
//            return AjaxResult.errorResult("您没有操作权限");
//        }
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("当前有订单不存在，请查证");
        }
        // 查看当前系统的抢单模式
        // 若是仅抢单模式则无法实行调度
        if (GrabOrderModeMan.getGrabOrderMode(orderInfo.getAgentId()) == GRAB_ORDER_MODE.ONLY_GRAB_MODE) {
            return AjaxResult.errorResult("当前仅抢单模式，无法调度");
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择配送员");
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }

        CityPostman postman = CityPostmanMemory.getInstance().getPostman(username);
        if (null == postman) {
            return AjaxResult.errorResult("当前账号无效");
        }
        if (ValidateUtil.isNotAbsInteger(postman.getIsWork())) {
            return AjaxResult.errorResult("您选择的账号未上班，请选择其他账号");
        }
        if (0 == postman.getIsWork()) {
            return AjaxResult.errorResult("您选择的账号未上班，请选择其他账号.");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
            return AjaxResult.errorResult("该账号未通过认证，无法派单");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
            UserInfo postmanUser = UserInfoMemory.getInstance().getUserInfo(username);
            if (null != postmanUser && null != postmanUser.getIsCert() && 0 == 1 - postmanUser.getIsCert()) {
                //已认证
            } else {
                return AjaxResult.errorResult("该账号未通过实名认证，无法派单");
            }
        }


        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(username);
            if (null == userWallet) {
                return AjaxResult.errorResult("该账号未缴纳押金，无法派单");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("该账号未缴纳押金，无法派单！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("该账号员缴纳的押金不足，请先缴纳押金");
            }
        }

        //判断当前订单状体
//        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
//        if (null == orderInfo) {
//            return AjaxResult.errorResult("当前订单不存在，请查证");
//        }
        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_REFUSED == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
                || (ORDER_STATUS.POSTMAN_ZHIDING == orderInfo.getOrderStatus() && (SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY == null || SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY == 0))
                || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                || (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType() && ORDER_STATUS.SUBMIT == orderInfo.getOrderStatus())) {
            return AjaxResult.errorResult("当前订单状态不允许操作");
        }

        // 如果已有配送员，先清除上次指定人员
        String lastPostman = orderInfo.getPostManUsername();
        if (username.equalsIgnoreCase(lastPostman)) {
            return AjaxResult.errorResult("骑手配送中，无需重复指定");
        }

        if (null != SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY && 0 == SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY) {
            // 只能指定一次
            if (ValidateUtil.isNotNull(lastPostman)) {
                return AjaxResult.errorResult("骑手配送中，不能重复指派");
            }
        }


        if (ValidateUtil.isNotNull(orderInfo.getShopCity())) {
            if (User.notHasCityAuth(user.getUsername(), orderInfo.getShopCity(), user.getUserType())) {
                return AjaxResult.errorResult("您没有访问该城市数据的权限");
            }
        }
//        if (ORDER_STATUS.POSTMAN_ZHIDING == orderInfo.getOrderStatus() && SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY != null && SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY == 1) {
//
//        }

//        //生成取货验证码
//        String verifyCode = getVerifyCode();
//        if (ValidateUtil.isNull(verifyCode)) {
//            return AjaxResult.errorResult("生成验证码失败，请稍后再试");
//        }

        //获取配送员信息
        UserInfo postmanInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == postmanInfo) {
            return AjaxResult.errorResult("当前配送员不存在，请查证后制定");
        }

        String grabCompanyIdStr = "";
//        if (StringUtils.isNotEmpty(companyIds)) {
//            Long companyId = calculateOrderGrabCompanyId(companyIds, username, orderInfo.getOrderType());
//            if (companyId == null) {
//                return AjaxResult.errorResult("未获取com_id");
//            }
//            grabCompanyIdStr = ",grabCompanyId = " + companyId;
//        }
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
            if (companyId == null) {
                return AjaxResult.errorResult("公司不能为空");
            }
            grabCompanyIdStr = ",grabCompanyId = " + companyId;
        }


        //当前配送员是否工作状态

        //todo 配送员送货个数 ，是否继续可以派单
        int orderSts = ORDER_STATUS.POSTMAN_ZHIDING;

        boolean isNeedAccept = true; // 骑手是否需要接单
        if (!OrderMan.systemOperatePostmanNeedAccept()) {
            isNeedAccept = false;
        }

        String postmanSureBySys = "";
        if (!isNeedAccept) {
            orderSts = ORDER_STATUS.POSTMAN_SURE;
            postmanSureBySys = ",postmanSureBySys=2 ";
        }

        // 父子订单的
        if (OrderMan.isMultipleParentOrder(orderNo)) {
            ResultInfo resultInfo = OrderMan.postmanSureMultipleOrder(orderInfo, companyId, orderNo, orderSts,
                    postmanSureBySys, postmanInfo, user.getUsername());
            if (resultInfo == null) {
                PostmanGrabMemory.getInstance().removeGrab(orderNo);
                return AjaxResult.errorResult("抢单失败");
            }
            if (!resultInfo.isSuccess()) {
                PostmanGrabMemory.getInstance().removeGrab(orderNo);
                return AjaxResult.errorResult(resultInfo.getError());
            }

            Connection conn = null;
            try {
                conn = UserDaoSql.getInstance().getConnection();
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            boolean isUpdateOrderPayInfo = false;
            try {

                conn.commit();
            } catch (Exception e) {
                PostmanGrabMemory.getInstance().removeGrab(user.getUsername(), orderInfo.getOrderNo());
                UserDaoSql.getInstance().rollback(conn);
                e.printStackTrace();
                return AjaxResult.errorResult(e.getMessage());
            } finally {
                UserDaoSql.getInstance().close(conn);
            }
            // 分成缓存
            if (isUpdateOrderPayInfo) {
                OrderPayMemory.getInstance().modify(orderNo);
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }
            }
            PostmanGrabMemory.getInstance().removeGrab(orderNo);
            return AjaxResult.successResult(); // 抢单成功
        }

        Connection con = null;
        try {
            con = UserDaoSql.getInstance().getConnection(true);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("数据库连接异常");
        }

        // 获取到时间进行处理
        Long time = DateUtils.getCurrTime();
        //保存到订单上
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(orderSts)
                .append(grabCompanyIdStr)
                .append(postmanSureBySys)
                .append(",updateUser = '").append(user.getUsername()).append("',postmanUsername='")
                .append(postmanInfo.getUsername()).append("',postmanName='").append(postmanInfo.getName()).append("',postmanPhone='")
                .append(postmanInfo.getTelPhone())
                .append("',postmanImageUrl='").append(postmanInfo.getSignPhoto()).append("' ");
        if (!isNeedAccept) {
            sb.append(" ,postmanSureTime=").append(time);
        }
        sb.append("  where delFlag = 0 and  orderNo ='").append(orderNo).append("'");

        OrderStatus orderStatus = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_ZHIDING, user.getUsername(), time);
        boolean isUpdatePayInfo = false;
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString(), con);
            UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, orderStatus, con);
            if (!isNeedAccept) {
                OrderStatus orderStatus2 = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_SURE, user.getUsername(), time);
                UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, orderStatus2, con);
            }
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            return AjaxResult.errorResult("指定的失败，请稍后");
        } finally {
            UserDaoSql.getInstance().close(con);
        }

        // 清除上次的骑手
        if (ValidateUtil.isNotNull(lastPostman)) {
            OrderInfoMemory.getInstance().removePostmanOrderInfo(lastPostman, orderNo);
        }
        //插入订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //修改订单缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        // 分成
        if (isUpdatePayInfo) {
            OrderPayMemory.getInstance().modify(orderNo);
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }

        //发送一条订单通知
//        Notice.publishOrderNotice(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），系统已指定配送员，请耐心等待");
//
//        //极光推送
//        JPushMessage jPushMessage = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），系统已指定配送员，请耐心等待");
//        jPushMessage.setPushUserType(JPushMessage.USER);//推给用户
//        JPushTask.jPushMessageList.add(jPushMessage);
        if (isNeedAccept) {
            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），系统已指定配送员，请耐心等待");
            Notice.publishNotice2Person(sysAppKey, postman.getUsername(), JPushMessage.POSTMAN, "-6", NoticeType.order, "订单信息", "您有新得系统指派订单,请注意查看", orderNo);
//            Notice.publishNotice2Person(sysAppKey, postman.getUsername(), JPushMessage.POSTMAN, NoticeType.order, "订单信息", "您有新得系统指派订单,请注意查看");
        } else {
            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已接单");
        }
        return AjaxResult.successResult();
    }

    //指定配送员 管理员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/postman/add")
    @ResponseBody
    public String order_postman_add(String token, String sysAppKey, Long companyId, String orderNo, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有权限
//        if (!User.hasServiceAuth(user.getUserType())) {
//            return AjaxResult.errorResult("您没有操作权限");
//        }
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("当前订单不存在，请查证");
        }
        // 查看当前系统的抢单模式
        // 若是仅抢单模式则无法实行调度
        if (GrabOrderModeMan.getGrabOrderMode(orderInfo.getAgentId()) == GRAB_ORDER_MODE.ONLY_GRAB_MODE) {
            return AjaxResult.errorResult("当前仅抢单模式，无法调度");
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择配送员");
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }

        CityPostman postman = CityPostmanMemory.getInstance().getPostman(username);
        if (null == postman) {
            return AjaxResult.errorResult("当前账号无效");
        }
        if (ValidateUtil.isNotAbsInteger(postman.getIsWork())) {
            return AjaxResult.errorResult("您选择的账号未上班，请选择其他账号");
        }
        if (0 == postman.getIsWork()) {
            return AjaxResult.errorResult("您选择的账号未上班，请选择其他账号.");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
            return AjaxResult.errorResult("该账号未通过认证，无法派单");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
            UserInfo postmanUser = UserInfoMemory.getInstance().getUserInfo(username);
            if (null != postmanUser && null != postmanUser.getIsCert() && 0 == 1 - postmanUser.getIsCert()) {
                //已认证
            } else {
                return AjaxResult.errorResult("该账号未通过实名认证，无法派单");
            }
        }


        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(username);
            if (null == userWallet) {
                return AjaxResult.errorResult("该账号未缴纳押金，无法派单");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("该账号未缴纳押金，无法派单！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("该账号员缴纳的押金不足，请先缴纳押金");
            }
        }

        //判断当前订单状体
//        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
//        if (null == orderInfo) {
//            return AjaxResult.errorResult("当前订单不存在，请查证");
//        }
        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_REFUSED == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
                || (ORDER_STATUS.POSTMAN_ZHIDING == orderInfo.getOrderStatus() && (SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY == null || SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY == 0))
                || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                || (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType() && ORDER_STATUS.SUBMIT == orderInfo.getOrderStatus())) {
            return AjaxResult.errorResult("当前订单状态不允许操作");
        }

        // 如果已有配送员，先清除上次指定人员
        String lastPostman = orderInfo.getPostManUsername();
        if (username.equalsIgnoreCase(lastPostman)) {
            return AjaxResult.errorResult("骑手配送中，无需重复指定");
        }

        if (null != SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY && 0 == SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY) {
            // 只能指定一次
            if (ValidateUtil.isNotNull(lastPostman)) {
                return AjaxResult.errorResult("骑手配送中，不能重复指派");
            }
        }


        if (ValidateUtil.isNotNull(orderInfo.getShopCity())) {
            if (User.notHasCityAuth(user.getUsername(), orderInfo.getShopCity(), user.getUserType())) {
                return AjaxResult.errorResult("您没有访问该城市数据的权限");
            }
        }
//        if (ORDER_STATUS.POSTMAN_ZHIDING == orderInfo.getOrderStatus() && SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY != null && SYS_SETTINGS.ASSIGN_ORDER_CAN_REPEATEDLY == 1) {
//
//        }

//        //生成取货验证码
//        String verifyCode = getVerifyCode();
//        if (ValidateUtil.isNull(verifyCode)) {
//            return AjaxResult.errorResult("生成验证码失败，请稍后再试");
//        }

        //获取配送员信息
        UserInfo postmanInfo = UserInfoMemory.getInstance().getUserInfo(username);
        if (null == postmanInfo) {
            return AjaxResult.errorResult("当前配送员不存在，请查证后制定");
        }

        String grabCompanyIdStr = "";
//        if (StringUtils.isNotEmpty(companyIds)) {
//            Long companyId = calculateOrderGrabCompanyId(companyIds, username, orderInfo.getOrderType());
//            if (companyId == null) {
//                return AjaxResult.errorResult("未获取com_id");
//            }
//            grabCompanyIdStr = ",grabCompanyId = " + companyId;
//        }
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
            if (companyId == null) {
                return AjaxResult.errorResult("公司不能为空");
            }
            grabCompanyIdStr = ",grabCompanyId = " + companyId;
        }


        //当前配送员是否工作状态

        //todo 配送员送货个数 ，是否继续可以派单
        int orderSts = ORDER_STATUS.POSTMAN_ZHIDING;

        boolean isNeedAccept = true; // 骑手是否需要接单
        if (!OrderMan.systemOperatePostmanNeedAccept()) {
            isNeedAccept = false;
        }

        String postmanSureBySys = "";
        if (!isNeedAccept) {
            orderSts = ORDER_STATUS.POSTMAN_SURE;
            postmanSureBySys = ",postmanSureBySys=2 ";
        }

        // 父子订单的
        if (OrderMan.isMultipleParentOrder(orderNo)) {
            ResultInfo resultInfo = OrderMan.postmanSureMultipleOrder(orderInfo, companyId, orderNo, orderSts,
                    postmanSureBySys, postmanInfo, user.getUsername());
            if (resultInfo == null) {
                PostmanGrabMemory.getInstance().removeGrab(orderNo);
                return AjaxResult.errorResult("抢单失败");
            }
            if (!resultInfo.isSuccess()) {
                PostmanGrabMemory.getInstance().removeGrab(orderNo);
                return AjaxResult.errorResult(resultInfo.getError());
            }

            Connection conn = null;
            try {
                conn = UserDaoSql.getInstance().getConnection();
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            boolean isUpdateOrderPayInfo = false;
            try {

                conn.commit();
            } catch (Exception e) {
                PostmanGrabMemory.getInstance().removeGrab(user.getUsername(), orderInfo.getOrderNo());
                UserDaoSql.getInstance().rollback(conn);
                e.printStackTrace();
                return AjaxResult.errorResult(e.getMessage());
            } finally {
                UserDaoSql.getInstance().close(conn);
            }
            // 分成缓存
            if (isUpdateOrderPayInfo) {
                OrderPayMemory.getInstance().modify(orderNo);
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }
            }
            PostmanGrabMemory.getInstance().removeGrab(orderNo);
            return AjaxResult.successResult(); // 抢单成功
        }

        Connection con = null;
        try {
            con = UserDaoSql.getInstance().getConnection(true);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("数据库连接异常");
        }

        // 获取到时间进行处理
        Long time = DateUtils.getCurrTime();
        //保存到订单上
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(orderSts)
                .append(grabCompanyIdStr)
                .append(postmanSureBySys)
                .append(",updateUser = '").append(user.getUsername()).append("',postmanUsername='")
                .append(postmanInfo.getUsername()).append("',postmanName='").append(postmanInfo.getName()).append("',postmanPhone='")
                .append(postmanInfo.getTelPhone())
                .append("',postmanImageUrl='").append(postmanInfo.getSignPhoto()).append("' ");
        if (!isNeedAccept) {
            sb.append(" ,postmanSureTime=").append(time);
        }
        sb.append("  where delFlag = 0 and  orderNo ='").append(orderNo).append("'");

        OrderStatus orderStatus = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_ZHIDING, user.getUsername(), time);
        boolean isUpdatePayInfo = false;
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString(), con);
            UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, orderStatus, con);
            if (!isNeedAccept) {
                OrderStatus orderStatus2 = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_SURE, user.getUsername(), time);
                UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, orderStatus2, con);
            }
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            return AjaxResult.errorResult("指定的失败，请稍后");
        } finally {
            UserDaoSql.getInstance().close(con);
        }

        // 清除上次的骑手
        if (ValidateUtil.isNotNull(lastPostman)) {
            OrderInfoMemory.getInstance().removePostmanOrderInfo(lastPostman, orderNo);
        }
        //插入订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //修改订单缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        // 分成
        if (isUpdatePayInfo) {
            OrderPayMemory.getInstance().modify(orderNo);
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }

        //发送一条订单通知
//        Notice.publishOrderNotice(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），系统已指定配送员，请耐心等待");
//
//        //极光推送
//        JPushMessage jPushMessage = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），系统已指定配送员，请耐心等待");
//        jPushMessage.setPushUserType(JPushMessage.USER);//推给用户
//        JPushTask.jPushMessageList.add(jPushMessage);
        if (isNeedAccept) {
            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），系统已指定配送员，请耐心等待");
            Notice.publishNotice2Person(sysAppKey, postman.getUsername(), JPushMessage.POSTMAN, "-6", NoticeType.order, "订单信息", "您有新得系统指派订单,请注意查看", orderNo);
//            Notice.publishNotice2Person(sysAppKey, postman.getUsername(), JPushMessage.POSTMAN, NoticeType.order, "订单信息", "您有新得系统指派订单,请注意查看");
        } else {
            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已接单");
        }
        return AjaxResult.successResult();
    }


    // 计算抢的订单所属公司的id
    private Long calculateOrderGrabCompanyId(String companyIds, String postmanUsername, Integer type) {
        if (StringUtils.isEmpty(companyIds) || type == null || StringUtils.isEmpty(postmanUsername)) {
            return null;
        }
        Set<Long> companyIdSet = CommonUtils.splitToSet(companyIds, Long.class);
        List<PostmanSignCompanyInfo> postmanSignCompanyInfos = PostmanSignCompanyMemory.getInstance().listOfPostman(postmanUsername, null, type, SIGN_COMPANY_STATUS.pass);
        Set<Long> validCompanyIdSet = postmanSignCompanyInfos == null ? null : postmanSignCompanyInfos.stream().map(a -> a.getCompanyId() == null ? null : PostCompanyMemory.getInstance().getById(a.getCompanyId()))
                .filter(company -> company != null).map(a -> a.getId()).collect(Collectors.toSet());
        if (validCompanyIdSet == null || validCompanyIdSet.isEmpty()) {
            return null;
        }
        validCompanyIdSet = validCompanyIdSet.stream().filter(id -> companyIdSet.contains(id)).collect(Collectors.toSet());
        return validCompanyIdSet == null || validCompanyIdSet.isEmpty() ? null : validCompanyIdSet.iterator().next();
    }

    //取消订单 并退款
    @RequestMapping(method = RequestMethod.POST, value = "/order/cancel")
    @ResponseBody
    public String order_cancel_admin(String token, String sysAppKey, String orderNo, String cancelReason, Integer refundAliWxPay) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasShopAuth(user.getUsername(), user.getUserType()) && !User.hasServiceAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限操作");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        //订单已经完成的  不能再取消
        if (0 == ORDER_STATUS.OVER - orderInfo.getOrderStatus()) {
            return AjaxResult.errorResult("当前订单已完成，无法退款");
        }


//        int orderStatus = ORDER_STATUS.CANCEL;
//        //是否已支付，已支付的需要退款
//        if (ValidateUtil.isAbsInteger(orderInfo.getIsPaid()) && 0 == orderInfo.getIsPaid() - 1) {//已经支付过了  需要退款
//
//            //todo  微信退款
////            if (ChannelUtils.wx.equals(orderInfo.getPayType())) {
////                return AjaxResult.errorResult("暂时不支持微信退款");
////            }
//
//            if (OrderPay.refund(orderInfo.getPayType(), orderInfo.getOrderNo(), orderInfo.getTotalPrice())) {
//                //退款成功了
//            } else {
//                return AjaxResult.errorResult("退款失败，请稍后再试");
//            }
//            orderStatus = ORDER_STATUS.PAYED_CANCEL;
//        } else {
//            orderStatus = ORDER_STATUS.CANCEL;
//        }
//
//        ResultInfo resultInfo = Order.cancelOrder(orderInfo, user.getUsername(), cancelReason, orderStatus, true);
//        if (null != resultInfo && !resultInfo.isSuccess()) {
//            return AjaxResult.errorResult(resultInfo.getError());
//        }

        //取消订单

        Boolean reAliWxPay = true;
        if (null == refundAliWxPay) {
            reAliWxPay = true;
        } else {
            reAliWxPay = 0 == refundAliWxPay ? false : true;
        }

        // 是生鲜类的合并订单的话先取消子订单
        if (OrderMan.isMultipleParentOrder(orderNo)) {
            HashSet<String> childSet = OrderInfoMemory.getInstance().listOfParentOrderNo(orderNo);
            for (String childOrderNo : childSet) {
                if (ValidateUtil.isNull(childOrderNo)) {
                    continue;
                }
                OrderInfo childOrder = OrderInfoMemory.getInstance().getOrderInfo(childOrderNo);
                if (null == childOrder) {
                    continue;
                }

                // 子订单不退款
                ResultInfo childResult = OrderMan.cancelOrder(sysAppKey, childOrder, user.getUsername(), cancelReason, false);
                if (null == childResult) {
                    return AjaxResult.errorResult("取消子订单失败，请稍后再试");
                }
                if (!childResult.isSuccess()) {
                    return AjaxResult.errorResult(childResult.getError());
                }
            }
        }

        ResultInfo resultInfo = OrderMan.cancelOrder(sysAppKey, orderInfo, user.getUsername(), cancelReason, reAliWxPay);
        if (null == resultInfo) {
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            //解绑小号
            MixComTelTask.unbindMap.put(orderNo, orderNo);
        }

        return AjaxResult.successResult();
    }


    //订单加急
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/urgent/add")
    @ResponseBody
    public String order_urgent_add(String token, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有权限
        if (!User.hasServiceAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }

        //判断当前订单状体
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("当前订单不存在，请查证");
        }
        if (null != orderInfo.getIsUrgent() && 0 == 1 - orderInfo.getIsUrgent()) {
            return AjaxResult.errorResult("当前订单已是加急状态，请耐心等待");
        }

        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL_BY_SYSTEM == orderInfo.getOrderStatus()) {
            return AjaxResult.errorResult("当前订单状态不允许操作");
        }

        //保存到订单上
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set isUrgent = 1")
                .append(",updateUser = '").append(user.getUsername()).append(" where delFlag = 0 and  orderNo ='").append(orderNo).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("加急失败，请稍后");
        }

        //修改缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        return AjaxResult.successResult();
    }

    //回访
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/visit/add")
    @ResponseBody
    public String order_visit_add(String token, String sysAppKey, String orderNo, String note) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有权限
        if (!User.hasServiceAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }

        //判断当前订单状体
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("当前订单不存在，请查证");
        }

        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL_BY_SYSTEM == orderInfo.getOrderStatus()) {
            return AjaxResult.errorResult("当前订单状态不允许操作");
        }

        if (null != orderInfo.getIsPaid() && 0 != 1 - orderInfo.getIsPaid()) {
            return AjaxResult.errorResult("订单还未支付");
        }
        //保存回访信息
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set extra2 = '").append(note)
                .append("' where orderNo = '").append(orderNo).append("' and delFlag = 0");
        StringBuffer sb2 = new StringBuffer();
        sb2.append("update ").append(PojoTables.ORDER_INFO_PRE).append(" set extra2 = '")
                .append(note).append("' where orderNo = '").append(orderNo).append("' and delFlag = 0");

        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
            UserDaoSql.getInstance().executeBySql(sb2.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //分成
        ResultInfo resultInfo = OrderPay.distributeMoney(orderInfo, orderNo, user.getUsername());
        if (null != resultInfo && !resultInfo.isSuccess()) {
            System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
        }

        //完成订单
        OrderMan.finishOrder(orderNo, user.getUsername(), orderInfo);


        //推送给锁匠
        if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType() && ValidateUtil.isNotNull(orderInfo.getPostManUsername())) {
//            JPushMessage jPushMessage2 = new JPushMessage(orderInfo.getPostManUsername(), "工单信息", "您的订单（工单编号：" + orderInfo.getOrderNo() + "）已回访，订单已完成");
//            jPushMessage2.setPushUserType(JPushMessage.POSTMAN);
//            JPushTask.jPushMessageList.add(jPushMessage2);
//            //发送一条订单通知
//            Notice.publishOrderNotice(orderInfo.getPostManUsername(), "工单信息", "您的订单（工单编号：" + orderInfo.getOrderNo() + "）已回访，订单已完成");

            Notice.publishNotice2Person(sysAppKey, orderInfo.getPostManUsername(), JPushMessage.USER, NoticeType.order, "工单信息", "您的订单（工单编号：" + orderInfo.getOrderNo() + "）已回访，订单已完成");

            //解绑小号
            MixComTelTask.unbindMap.put(orderNo, orderNo);
        }

        return AjaxResult.successResult();
    }

    // 获取骑手申诉评价申诉列表
    @RequestMapping(method = RequestMethod.POST, value = "/admin/comment/need/deal/list")
    @ResponseBody
    public String order_comment_apply_list(String token, Integer page, Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有权限
        if (!User.hasServiceAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        // 添加
        List<OrderCommentInfo> orderCommentInfoList = OrderCommentMemory.getInstance().listOPostmanDelApply();
        if (ValidateUtil.isAbsList(orderCommentInfoList)) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(orderCommentInfoList, page, size);
            List<OrderCommentInfo> list = (List<OrderCommentInfo>) pageList.list;
            if (ValidateUtil.isAbsList(list)) {
                List<OrderCommentInfoVO> commentInfoVOList = new ArrayList<>();
                for (OrderCommentInfo commentInfo : list) {
                    if (commentInfo == null) {
                        continue;
                    }
                    OrderCommentInfoVO orderCommentInfoVO = new OrderCommentInfoVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(commentInfo, orderCommentInfoVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    // 处理图片
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getImage1Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getImage1Url())) {
                        orderCommentInfoVO.setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getImage1Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getImage2Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getImage2Url())) {
                        orderCommentInfoVO.setImage2Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getImage2Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getImage3Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getImage3Url())) {
                        orderCommentInfoVO.setImage3Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getImage3Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getImage4Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getImage4Url())) {
                        orderCommentInfoVO.setImage4Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getImage4Url());
                    }
                    // 申诉图片
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getApplyImage1Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getApplyImage1Url())) {
                        orderCommentInfoVO.setApplyImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getApplyImage1Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getApplyImage2Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getApplyImage2Url())) {
                        orderCommentInfoVO.setApplyImage2Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getApplyImage2Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getApplyImage3Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getApplyImage3Url())) {
                        orderCommentInfoVO.setApplyImage3Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getApplyImage3Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getApplyImage4Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getApplyImage4Url())) {
                        orderCommentInfoVO.setApplyImage4Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getApplyImage4Url());
                    }
                    commentInfoVOList.add(orderCommentInfoVO);
                }
                return AjaxResult.successResult(pageList.totalCount, pageList.size, commentInfoVOList);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }

    // 管理员处理申诉
    @RequestMapping(method = RequestMethod.POST, value = "/admin/comment/deal/apply")
    @ResponseBody
    public String order_comment_pass_apply(String token, Long id, Integer type) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有权限
        if (!User.hasServiceAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        // 同意还是
        if (ValidateUtil.isNotAbsInteger(type)) {
            return AjaxResult.errorResult("请选择操作类型");
        }
        if (type != COMMENT_APPLY.PASS && type != COMMENT_APPLY.NO) {
            return AjaxResult.errorResult("未知的操作类型");
        }
        // 评论加测
        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("id不能为空");
        }
        OrderCommentInfo commentInfo = OrderCommentMemory.getInstance().get(id);
        if (commentInfo == null) {
            return AjaxResult.errorResult("订单信息不存在");
        }
        if (commentInfo.getDelApply() != null && ((commentInfo.getDelApply() == COMMENT_APPLY.PASS || commentInfo.getDelApply() == COMMENT_APPLY.NO))) {
            return AjaxResult.errorResult("您已经处理过该申诉了");
        }
        if (commentInfo.getDelApply() != null && (commentInfo.getDelApply() != COMMENT_APPLY.APPLY)) {
            return AjaxResult.errorResult("骑手未发起申诉申请");
        }
        StringBuffer sql = new StringBuffer();
        sql.append(" update ").append(PojoTables.ORDER_COMMENT).append(" set delApply = ").append(type);
        if (type == COMMENT_APPLY.PASS) {
            sql.append(",delFlag = 1 ");
        }
        sql.append(" where id =").append(id);
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("处理失败，请稍后重试");
        }
        return AjaxResult.successResult();
    }

    // 管理严删除评论信息
    @RequestMapping(method = RequestMethod.POST, value = "/admin/comment/del")
    @ResponseBody
    public String order_comment_admin_del(String token, Long id) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有权限
        if (!User.hasServiceAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        // 评论加测
        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("id不能为空");
        }
        OrderCommentInfo commentInfo = OrderCommentMemory.getInstance().get(id);
        if (commentInfo == null) {
            return AjaxResult.errorResult("订单信息不存在");
        }
        StringBuffer sql = new StringBuffer();
        sql.append(" update ").append(PojoTables.ORDER_COMMENT).append(" set ");
        sql.append(" delFlag = 1 ");
        sql.append(" where id =").append(id);
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("处理失败，请稍后重试");
        }
        return AjaxResult.successResult();
    }

    // 删除整条订单的记录
    @RequestMapping(method = RequestMethod.POST, value = "/admin/comment/orderNo/del")
    @ResponseBody
    public String order_comment_admin_del_orderNo(String token, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
//        验证是否有权限
        if (!User.hasServiceAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        // 评论加测
        if (!ValidateUtil.isNotNull(orderNo)) {
            return AjaxResult.errorResult("订单编号不能为空");
        }
        List<OrderCommentInfo> listByOrderNo = OrderCommentMemory.getInstance().getOrderCommentListByOrderNo(orderNo);
        if (!ValidateUtil.isAbsList(listByOrderNo)) {
            return AjaxResult.errorResult("评论信息不存在");
        }
        StringBuffer sql = new StringBuffer();
        sql.append(" update ").append(PojoTables.ORDER_COMMENT).append(" set ");
        sql.append(" delFlag = 1 ");
        sql.append(" where orderNo ='").append(orderNo).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("处理失败，请稍后重试");
        }

        return AjaxResult.successResult();
    }

    // 退单到大厅
    // 订单退回到订大厅内
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/back")
    @ResponseBody
    public String order_postman_back(String token, String sysAppKey, String orderNo) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("订单编号不能为空");
        }
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (info == null) {
            return AjaxResult.errorResult("未获取到订单信息");
        }
        if (info.getOrderStatus() != ORDER_STATUS.POSTMAN_SURE
                && info.getOrderStatus() != ORDER_STATUS.SHOP_SURE
                && info.getOrderStatus() != ORDER_STATUS.POSTMAN_DAODIAN
                && info.getOrderStatus() != ORDER_STATUS.POSTMAN_ARRIVED // 到达指定位置
                && info.getOrderStatus() != ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP) {
            return AjaxResult.errorResult("当前状态下不能操作");
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (postman == null) {
            return AjaxResult.errorResult("未获取到配送员信息");
        }
        try {
            OrderMan.postmanBackOrder(info, user, postman, false);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        return AjaxResult.successResult();
    }


    // todo : 店铺评论审核
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/comment/verify")
    @ResponseBody
    public String shop_comment_verify(String sysAppKey, String token, Long id, Integer verifyState) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("评论id不能为空");
        }
        if (verifyState == null) {
            verifyState = COMMENT_VERIFY_STATE.COMMENT_PASS;
        }

        QueryCondition query = QueryCondition.getInstance();
        query.addCondition(Expression.getInstance().addChild("delFlag", 0).addChild("id", id));
        String sql = DaoUtils.getSql(PojoTables.ShopComment, query);

        // 查询
        ShopCommentInfo info = null;
        try {
            info = (ShopCommentInfo) UserDaoSql.getInstance().getObject(ShopCommentInfo.class, sql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        if (info == null || info.getVerifyState() != 1) {
            return AjaxResult.errorResult("当前审核状态不允许操作");
        }
        if (verifyState != COMMENT_VERIFY_STATE.COMMENT_BACK && verifyState != COMMENT_VERIFY_STATE.COMMENT_PASS) {
            return AjaxResult.errorResult("无效的操作,请核实后操作");
        }
        StringBuffer sqlBu = new StringBuffer();
        sqlBu.append("update ")
                .append(PojoTables.ShopComment)
                .append(" set  updateUser = '").append(user.getUsername()).append("'")
                .append(", verifyState =").append(verifyState)
                .append(" where id =").append(id).append(" and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sqlBu.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        // 店铺的缓存
        if (verifyState == COMMENT_VERIFY_STATE.COMMENT_PASS && ValidateUtil.isID(info.getShopId())) {
            ShopMemory.getInstance().setComment(info.getShopId(), info);
        }
        return AjaxResult.successResult();
    }

    // ************************业务逻辑处理***************************
    // 管理后台接聚合订单问题
    public void sure_parent_order(String sysAppKey, String orderNo, String opUsername) throws Exception {
        HashSet<String> hashSet = OrderInfoMemory.getInstance().listOfParentOrderNo(orderNo);
        if (hashSet == null || hashSet.size() == 0) {
            return;
        }
        for (String oN : hashSet) {
            OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(oN);
            if (info == null) {
                continue;
            }
            if (info.getOrderStatus() != ORDER_STATUS.PAYED) {
                continue;
            }
            if (info.getShopId() == null) {
                throw new Exception("未获取到店铺信息");
            }
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(info.getShopId());
            if (shopInfo == null) {
                throw new Exception("未获取到店铺信息id[" + info.getShopId() + "]");
            }
            ResultInfo resultInfo = ShopOrderController.sureOrder(sysAppKey, shopInfo, info, opUsername, false);
            if (resultInfo == null || !resultInfo.isSuccess()) {
                throw new Exception(resultInfo.getError());
            }
        }
    }
}
